package sequence

import (
	
	
	

	
)

const (
	SequenceDiagramKeyword = "sequenceDiagram"
	SolidArrowSyntax       = "->>"
	DottedArrowSyntax      = "-->>"
)

var (
	// participantRegex matches participant declarations: participant [rest] or
	// actor [rest]. mermaid renders an actor as a stick figure; in ASCII both
	// forms draw the same labelled box. The rest ([ID] [as Label]) is split by
	// parseParticipant, because IDs may contain spaces (mermaid's ID lexer
	// state allows them: "participant cron job as Cron").
	participantRegex = regexp.MustCompile(`(?i)^\s*(?:participant|actor)\s+(.+)$`)

	// participantAsRegex splits "ID as Label" at the FIRST " as ", matching
	// mermaid's lexer for whitespace-free IDs. For IDs containing spaces this
	// is a deliberate extension: mermaid's alias rule only fires for
	// whitespace-free IDs, so it would read the whole line as one long name.
	participantAsRegex = regexp.MustCompile(`(?i)^(.*?\S)\s+as\s+(.+)$`)

	// fragmentKeywordRegex guards message parsing: mermaid lexes fragment
	// keywords before actor names, so a line whose first word is one of them
	// is never a message — even when its label contains an arrow and a colon
	// ("else fall back -> retry: yes").
	fragmentKeywordRegex = regexp.MustCompile(`(?i)^(loop|opt|alt|par|critical|break|rect|else|and|option|end)\b`)

	// arrowTokens are mermaid's ten message arrows, longest first so that at
	// any position the longest token wins (e.g. "-->>" is never read as
	// "-->", "--)" never as "--" + ")").
	arrowTokens = []string{"<<-->>", "<<->>", "-->>", "--x", "--)", "-->", "->>", "-x", "-)", "->"}

	// autonumberRegex matches the autonumber directive
	autonumberRegex = regexp.MustCompile(`(?i)^\s*autonumber\s*$`)

	// fragmentStartRegex matches the opening line of a control-flow fragment,
	// e.g. "loop every minute", "opt is premium", "alt is valid". Group 1 is the
	// keyword, group 2 is the (optional) label describing the condition.
	fragmentStartRegex = regexp.MustCompile(`(?i)^\s*(loop|opt|alt|par|critical|break|rect)\b\s*(.*)$`)

	// fragmentDividerRegex matches a section divider inside a fragment: "else"
	// (alt), "and" (par), or "option" (critical). Group 1 is the keyword, group 2
	// the (optional) label for the following section.
	fragmentDividerRegex = regexp.MustCompile(`(?i)^\s*(else|and|option)\b\s*(.*)$`)

	// rectColorRegex strips a leading rgb()/rgba() colour argument from a rect's
	// label (ASCII can't render the fill; PR6 draws a plain frame).
	rectColorRegex = regexp.MustCompile(`(?i)^\s*rgba?\([^)]*\)\s*`)

	// fragmentEndRegex matches the "end" line that closes a fragment.
	fragmentEndRegex = regexp.MustCompile(`(?i)^\s*end\s*$`)

	// boxStartRegex matches a participant-group opener: `box [color] [title]`.
	// Like participant/actor (and mermaid itself), the keyword wins at line
	// start, so a participant named "box …" can only message via quoting.
	boxStartRegex = regexp.MustCompile(`(?i)^\s*box(?:\s+(.*))?$`)

	// boxColorFuncRegex matches a functional color prefix on a box line:
	// rgb(…), rgba(…), hsl(…), hsla(…) — the argument list may contain spaces.
	boxColorFuncRegex = regexp.MustCompile(`(?i)^(?:rgba?|hsla?)\s*\([^)]*\)`)

	// boxHexColorRegex matches a leading #hex color token.
	boxHexColorRegex = regexp.MustCompile(`^#[0-9a-fA-F]{3,8}\b`)

	// activationRegex matches the standalone activation keywords:
	// `activate A` / `deactivate A`. Group 1 is the keyword, group 2 the name.
	activationRegex = regexp.MustCompile(`(?i)^\s*(activate|deactivate)\s+(.+)$`)

	// createRegex matches `create participant X` / `create actor X as Y`: the
	// participant appears at the message that follows.
	createRegex = regexp.MustCompile(`(?i)^\s*create\s+(participant|actor)\s+(.+)$`)

	// destroyRegex matches `destroy X`: X's lifeline ends at the message that
	// follows.
	destroyRegex = regexp.MustCompile(`(?i)^\s*destroy\s+(.+)$`)

	// brTagRegex matches <br> variants, which mermaid treats as line breaks;
	// single-line ASCII titles render them as spaces.
	brTagRegex = regexp.MustCompile(`(?i)<br\s*/?>`)

	// noteRegex matches note annotations: "Note over A: text", "note left of A:
	// text", "Note over A,B: text" (case-insensitive keyword). Group 1 is the
	// placement, group 2 the participant list, group 3 the text.
	noteRegex = regexp.MustCompile(`(?i)^\s*note\s+(right of|left of|over)\s+([^:]+?)\s*:\s*(.*)$`)
)

// SequenceDiagram represents a parsed sequence diagram.
type SequenceDiagram struct {
	Participants []*Participant
	// Messages is the flat list of every message arrow, in source order and
	// independent of any fragment nesting. Kept for callers that only care
	// about the messages themselves (and for backward compatibility).
	Messages []*Message
	// Events is the ordered body of the diagram used for rendering: each entry
	// is either a message or a fragment boundary. Walking Events reproduces the
	// original source order, including where loop/opt blocks open and close.
	Events     []Event
	Autonumber bool
	// Boxes are participant groups declared with `box [color] [title] … end`;
	// each wraps a contiguous run of participants (they are declared inside
	// the block, so contiguity is inherent).
	Boxes []*Box
	// Created lists participants introduced by a `create` statement, whose
	// lifelines begin partway down the diagram rather than at the top.
	Created []*Participant
}

// Box is a participant group drawn as a frame around its participants'
// columns. mermaid fills it with a color; ASCII draws a plain frame, so the
// color is parsed (to keep it out of the title) and discarded.
type Box struct {
	Title       string
	First, Last int // participant Index range, inclusive
}

// FragmentType identifies a control-flow fragment (a "framed" block of
// messages) such as a loop or an optional section.
type FragmentType int

const (
	FragmentLoop     FragmentType = iota // loop ... end
	FragmentOpt                          // opt ... end
	FragmentAlt                          // alt ... else ... end
	FragmentPar                          // par ... and ... end
	FragmentCritical                     // critical ... option ... end
	FragmentBreak                        // break ... end
	FragmentRect                         // rect ... end
)

func ( FragmentType) () string {
	switch  {
	case FragmentLoop:
		return "loop"
	case FragmentOpt:
		return "opt"
	case FragmentAlt:
		return "alt"
	case FragmentPar:
		return "par"
	case FragmentCritical:
		return "critical"
	case FragmentBreak:
		return "break"
	case FragmentRect:
		return "rect"
	default:
		return fmt.Sprintf("FragmentType(%d)", int())
	}
}

// fragmentKeywords maps an opener keyword to its fragment type.
var fragmentKeywords = map[string]FragmentType{
	"loop": FragmentLoop, "opt": FragmentOpt, "alt": FragmentAlt,
	"par": FragmentPar, "critical": FragmentCritical,
	"break": FragmentBreak, "rect": FragmentRect,
}

// dividerKeywords maps a section-divider keyword to the fragment type it must
// appear inside.
var dividerKeywords = map[string]FragmentType{
	"else": FragmentAlt, "and": FragmentPar, "option": FragmentCritical,
}

// Fragment describes the opening of a control-flow block: its kind and the
// optional condition text shown in the frame's label tab.
type Fragment struct {
	Type  FragmentType
	Label string
}

// EventKind tags each Event in the diagram body.
type EventKind int

const (
	EventMessage         EventKind = iota // a message arrow
	EventFragmentStart                    // the opening line of a loop/opt/alt block
	EventFragmentDivider                  // an "else" section divider within an alt
	EventFragmentEnd                      // the matching "end" line
	EventNote                             // a note annotation
	EventActivate                         // a participant becomes active
	EventDeactivate                       // a participant stops being active
	EventCreate                           // a participant's lifeline begins here
	EventDestroy                          // a participant's lifeline ends here
)

func ( EventKind) () string {
	switch  {
	case EventMessage:
		return "message"
	case EventFragmentStart:
		return "fragment-start"
	case EventFragmentDivider:
		return "fragment-divider"
	case EventFragmentEnd:
		return "fragment-end"
	case EventNote:
		return "note"
	case EventActivate:
		return "activate"
	case EventDeactivate:
		return "deactivate"
	case EventCreate:
		return "create"
	case EventDestroy:
		return "destroy"
	default:
		return fmt.Sprintf("EventKind(%d)", int())
	}
}

// Event is one item in the diagram body. Exactly one payload field is set:
// Message when Kind is EventMessage, Fragment when Kind is EventFragmentStart,
// Note when Kind is EventNote. An EventFragmentEnd carries no payload; it just
// marks where a block closes.
type Event struct {
	Kind     EventKind
	Message  *Message
	Fragment *Fragment
	Note     *Note
	// Participant is set for EventActivate / EventDeactivate: the lifeline
	// whose activation period starts or ends here.
	Participant *Participant
}

// NotePlacement describes where a note box sits relative to its participant(s).
type NotePlacement int

const (
	NoteOver    NotePlacement = iota // note over A  /  note over A,B
	NoteLeftOf                       // note left of A
	NoteRightOf                      // note right of A
)

// Note is an annotation box drawn over or beside participant lifelines.
type Note struct {
	Placement    NotePlacement
	Participants []*Participant // one participant, or two for "over A,B"
	Text         string
}

type Participant struct {
	ID    string
	Label string
	Index int
	// declared is true once a participant/actor statement names this
	// participant, as opposed to it being created implicitly by a message.
	declared bool
}

type Message struct {
	From      *Participant
	To        *Participant
	Label     string
	ArrowType ArrowType
	// CentralFrom / CentralTo mark central connections (mermaid's "()" on
	// either side of the arrow): a circle drawn where the message meets that
	// participant's lifeline.
	CentralFrom bool
	CentralTo   bool
	Number      int // Message number when autonumber is enabled (0 means no number)
}

type ArrowType int

const (
	SolidArrow          ArrowType = iota // ->>    solid line with an arrowhead
	DottedArrow                          // -->>   dotted line with an arrowhead
	SolidOpen                            // ->     solid line, no arrowhead
	DottedOpen                           // -->    dotted line, no arrowhead
	SolidCross                           // -x     solid line, cross head (lost/failed message)
	DottedCross                          // --x    dotted line, cross head
	SolidPoint                           // -)     solid line, open point head (async message)
	DottedPoint                          // --)    dotted line, open point head
	BidirectionalSolid                   // <<->>  solid line, arrowheads both ends
	BidirectionalDotted                  // <<-->> dotted line, arrowheads both ends
)

// isDotted reports whether the arrow is drawn with a dotted (rather than solid)
// line.
func ( ArrowType) () bool {
	switch  {
	case DottedArrow, DottedOpen, DottedCross, DottedPoint, BidirectionalDotted:
		return true
	}
	return false
}

// isBidirectional reports whether the arrow carries a head at the source end
// too (mermaid's <<->> and <<-->>).
func ( ArrowType) () bool {
	return  == BidirectionalSolid ||  == BidirectionalDotted
}

// head returns the glyph drawn where the arrow meets the target lifeline, and
// false for the open forms (-> and -->), which are drawn as a plain line
// touching the lifeline. rightward selects the direction the head points.
func ( ArrowType) ( BoxChars,  bool) (rune, bool) {
	switch  {
	case SolidArrow, DottedArrow, BidirectionalSolid, BidirectionalDotted:
		if  {
			return .ArrowRight, true
		}
		return .ArrowLeft, true
	case SolidCross, DottedCross:
		return .CrossHead, true
	case SolidPoint, DottedPoint:
		if  {
			return .PointRight, true
		}
		return .PointLeft, true
	}
	return 0, false
}

func ( ArrowType) () string {
	switch  {
	case SolidArrow:
		return "solid"
	case DottedArrow:
		return "dotted"
	case SolidOpen:
		return "solid-open"
	case DottedOpen:
		return "dotted-open"
	case SolidCross:
		return "solid-cross"
	case DottedCross:
		return "dotted-cross"
	case SolidPoint:
		return "solid-point"
	case DottedPoint:
		return "dotted-point"
	case BidirectionalSolid:
		return "bidirectional-solid"
	case BidirectionalDotted:
		return "bidirectional-dotted"
	default:
		return fmt.Sprintf("ArrowType(%d)", int())
	}
}

func ( string) bool {
	 := strings.Split(, "\n")
	for ,  := range  {
		 := strings.TrimSpace()
		if  == "" || strings.HasPrefix(, "%%") {
			continue
		}
		return hasSequenceKeyword()
	}
	return false
}

// hasSequenceKeyword reports whether a line is the sequenceDiagram declaration,
// case-insensitively (mermaid's sequence grammar is case-insensitive). The
// keyword must stand as a whole token — followed by whitespace or end of line —
// so a node id like "sequenceDiagramFoo" in a flowchart isn't misrouted here.
func hasSequenceKeyword( string) bool {
	 := strings.ToLower(strings.TrimSpace())
	 := strings.ToLower(SequenceDiagramKeyword)
	if !strings.HasPrefix(, ) {
		return false
	}
	 := [len():]
	return  == "" || [0] == ' ' || [0] == '\t'
}

func ( string) (*SequenceDiagram, error) {
	 = strings.TrimSpace()
	if  == "" {
		return nil, fmt.Errorf("empty input")
	}

	 := diagram.SplitLines()
	 := diagram.RemoveComments()
	if len() == 0 {
		return nil, fmt.Errorf("no content found")
	}

	if !hasSequenceKeyword(strings.TrimSpace([0])) {
		return nil, fmt.Errorf("expected %q keyword", SequenceDiagramKeyword)
	}
	 = [1:]

	 := &SequenceDiagram{
		Participants: []*Participant{},
		Messages:     []*Message{},
		Autonumber:   false,
	}
	 := make(map[string]*Participant)
	// openFragments is a stack of the fragment types currently open, so we can
	// reject an "end"/"else" with no matching opener, validate that "else" only
	// appears inside an "alt", and detect an opener with no matching "end".
	var  []FragmentType
	// openBox is the box block currently being declared, if any. mermaid's
	// grammar allows only participant declarations inside a box, and boxes
	// cannot nest.
	var  *Box
	// active counts each participant's open activation periods, so deactivating
	// an inactive participant is an error and stacked activations balance.
	 := map[*Participant]int{}
	// pendingCreate / pendingDestroy hold a participant named by a `create` or
	// `destroy` statement. mermaid attaches each to the message that follows,
	// which must involve that participant.
	var ,  *Participant
	var ,  int

	for ,  := range  {
		 := strings.TrimSpace()
		if  == "" {
			continue
		}

		// Inside a box block only participant/actor declarations (and the
		// closing "end") are valid, so handle that mode first.
		if  != nil {
			if fragmentEndRegex.MatchString() {
				 = nil
				continue
			}
			if boxStartRegex.MatchString() {
				return nil, fmt.Errorf("line %d: boxes cannot nest", +2)
			}
			, ,  := .parseParticipant(, )
			if  != nil {
				return nil, fmt.Errorf("line %d: %w", +2, )
			}
			if ! {
				return nil, fmt.Errorf("line %d: only participant declarations are allowed inside a box: %q", +2, )
			}
			if .First == -1 {
				.First = .Index
			}
			.Last = .Index
			continue
		}

		// Check for autonumber directive
		if autonumberRegex.MatchString() {
			.Autonumber = true
			continue
		}

		// A box opener starts a participant group; its optional color is
		// parsed away (no ASCII meaning) so it never leaks into the title.
		if  := boxStartRegex.FindStringSubmatch();  != nil {
			 = &Box{Title: parseBoxTitle([1]), First: -1}
			.Boxes = append(.Boxes, )
			continue
		}

		// Notes carry no arrow, so they never collide with messages; a
		// placement keyword is required, so a participant named "Note" (e.g.
		// "Note->>B: hi") still parses as a message further down.
		if  := noteRegex.FindStringSubmatch();  != nil {
			 := NoteOver
			switch strings.ToLower([1]) { // keyword may be any case
			case "left of":
				 = NoteLeftOf
			case "right of":
				 = NoteRightOf
			}
			var  []*Participant
			for ,  := range strings.Split([2], ",") {
				 = strings.Trim(strings.TrimSpace(), `"`)
				if  != "" {
					 = append(, .getParticipant(, ))
				}
			}
			if len() == 0 {
				return nil, fmt.Errorf("line %d: note without a participant", +2)
			}
			// Mermaid allows an optional wrap:/nowrap: prefix on note text;
			// wrapping is irrelevant for single-line ASCII, so just strip it.
			 := strings.TrimSpace([3])
			for ,  := range []string{"nowrap:", "wrap:"} {
				if strings.HasPrefix(strings.ToLower(), ) {
					 = strings.TrimSpace([len():])
					break
				}
			}
			.Events = append(.Events, Event{
				Kind: EventNote,
				Note: &Note{Placement: , Participants: , Text: },
			})
			continue
		}

		if , ,  := .parseParticipant(, );  != nil {
			return nil, fmt.Errorf("line %d: %w", +2, )
		} else if  {
			continue
		}

		// Messages are checked before fragment keywords so a participant named
		// "loop"/"opt"/"end" (e.g. "loop->>B: hi") is still read as a message —
		// only bare openers like "loop retry" fall through to the checks below.
		 := len(.Events)
		if ,  := .parseMessageEvent(, , );  != nil {
			return nil, fmt.Errorf("line %d: %w", +2, )
		} else if  {
			// A create/destroy statement binds to this, the next message, which
			// must involve its participant: mermaid requires a created
			// participant to be the recipient (it cannot send the message that
			// brings it into being) and a destroyed one to be at either end.
			 := .Events[].Message
			if  := ;  != nil {
				 = nil
				if .To !=  {
					return nil, fmt.Errorf("line %d: the created participant %q must receive the message that creates it", , .ID)
				}
				// The lifeline starts at this message, so the event precedes it.
				.Events = append(.Events, Event{})
				copy(.Events[+1:], .Events[:])
				.Events[] = Event{Kind: EventCreate, Participant: }
			}
			if  := ;  != nil {
				 = nil
				if .From !=  && .To !=  {
					return nil, fmt.Errorf("line %d: the destroyed participant %q is not involved in the following message", , .ID)
				}
				// The lifeline ends after this message.
				.Events = append(.Events, Event{Kind: EventDestroy, Participant: })
			}
			continue
		}

		// `create participant X` / `create actor X as Y`: declare X, then bind
		// it to the message that follows.
		if  := createRegex.FindStringSubmatch();  != nil {
			// mermaid rejects creating an id that already exists, even one only
			// implied by an earlier message, and points at AS aliases instead.
			if ,  := parseName(nameBeforeAlias([2]));  && [] != nil {
				return nil, fmt.Errorf("line %d: cannot create participant %q: the id already exists, use an \"as\" alias for a distinct participant", +2, )
			}
			,  := .declareParticipant([2], )
			if  != nil {
				return nil, fmt.Errorf("line %d: %w", +2, )
			}
			,  = , +2
			.Created = append(.Created, )
			continue
		}

		// `destroy X`: end X's lifeline at the message that follows.
		if  := destroyRegex.FindStringSubmatch();  != nil {
			,  := parseName([1])
			if ! {
				return nil, fmt.Errorf("line %d: invalid participant name %q", +2, [1])
			}
			,  := []
			if ! {
				return nil, fmt.Errorf("line %d: cannot destroy unknown participant %q", +2, )
			}
			,  = , +2
			continue
		}

		// Standalone activation keywords. Checked after messages so a
		// participant named "activate …" can still send one.
		if  := activationRegex.FindStringSubmatch();  != nil {
			,  := parseName([2])
			if ! {
				return nil, fmt.Errorf("line %d: invalid participant name %q", +2, [2])
			}
			 := .getParticipant(, )
			if strings.EqualFold([1], "activate") {
				[]++
				.Events = append(.Events, Event{Kind: EventActivate, Participant: })
			} else {
				if [] == 0 {
					return nil, fmt.Errorf("line %d: trying to deactivate an inactive participant %q", +2, .ID)
				}
				[]--
				.Events = append(.Events, Event{Kind: EventDeactivate, Participant: })
			}
			continue
		}

		// A fragment opener (loop/opt/alt/par/critical/break/rect) starts a block.
		if  := fragmentStartRegex.FindStringSubmatch();  != nil {
			 := fragmentKeywords[strings.ToLower([1])]
			 := strings.TrimSpace([2])
			// rect's argument is a fill colour we can't render in ASCII; drop it
			// so the frame is drawn plain (colour support is a follow-up).
			if  == FragmentRect {
				 = strings.TrimSpace(rectColorRegex.ReplaceAllString(, ""))
			}
			.Events = append(.Events, Event{
				Kind:     EventFragmentStart,
				Fragment: &Fragment{Type: , Label: },
			})
			 = append(, )
			continue
		}

		// A section divider: "else" (alt), "and" (par), "option" (critical). It
		// must sit directly inside the matching fragment type.
		if  := fragmentDividerRegex.FindStringSubmatch();  != nil {
			 := dividerKeywords[strings.ToLower([1])]
			if len() == 0 || [len()-1] !=  {
				return nil, fmt.Errorf("line %d: %q outside a matching %s block", +2, , )
			}
			.Events = append(.Events, Event{
				Kind:     EventFragmentDivider,
				Fragment: &Fragment{Type: , Label: strings.TrimSpace([2])},
			})
			continue
		}

		// "end" closes the most recently opened fragment.
		if fragmentEndRegex.MatchString() {
			if len() == 0 {
				return nil, fmt.Errorf("line %d: %q without a matching fragment opener", +2, )
			}
			.Events = append(.Events, Event{Kind: EventFragmentEnd})
			 = [:len()-1]
			continue
		}

		return nil, fmt.Errorf("line %d: invalid syntax: %q", +2, )
	}

	if  := ;  != nil {
		return nil, fmt.Errorf("line %d: the created participant %q must be followed by a message involving it", , .ID)
	}
	if  := ;  != nil {
		return nil, fmt.Errorf("line %d: the destroyed participant %q must be followed by a message involving it", , .ID)
	}
	if  != nil {
		return nil, fmt.Errorf("unclosed box: missing \"end\"")
	}
	if len() > 0 {
		return nil, fmt.Errorf("unclosed fragment: missing %d \"end\"", len())
	}

	if len(.Participants) == 0 {
		return nil, fmt.Errorf("no participants found")
	}

	// A box declared with no participants has nothing to frame; drop it.
	 := .Boxes[:0]
	for ,  := range .Boxes {
		if .First >= 0 {
			 = append(, )
		}
	}
	.Boxes = 

	return , nil
}

// parseParticipant handles a participant/actor declaration. It reports whether
// the line was one, and returns the participant it created or claimed so a
// caller (the box block) can record which lifeline was declared.
func ( *SequenceDiagram) ( string,  map[string]*Participant) (*Participant, bool, error) {
	 := participantRegex.FindStringSubmatch()
	if  == nil {
		return nil, false, nil
	}
	,  := .declareParticipant([1], )
	return , true, 
}

// nameBeforeAlias returns the id portion of an "ID [as Label]" declaration.
func nameBeforeAlias( string) string {
	 = strings.TrimSpace()
	if  := participantAsRegex.FindStringSubmatch();  != nil {
		return [1]
	}
	return 
}

// declareParticipant records a participant from the "[ID] [as Label]" part of a
// declaration, shared by participant/actor statements and by `create`.
func ( *SequenceDiagram) ( string,  map[string]*Participant) (*Participant, error) {
	 = strings.TrimSpace()
	 := 
	 := ""
	if  := participantAsRegex.FindStringSubmatch();  != nil {
		,  = [1], [2]
	}
	,  := parseName()
	if ! {
		return nil, fmt.Errorf("invalid participant name %q", )
	}
	if  == "" {
		 = 
	}
	 = strings.Trim(, `"`)

	// A participant already created implicitly by an earlier message may be
	// declared afterwards to give it a label or put it in a box, as mermaid
	// allows (addActor updates an existing actor). Only declaring the same
	// participant twice is an error.
	if ,  := [];  {
		if .declared {
			return nil, fmt.Errorf("duplicate participant %q", )
		}
		.declared = true
		.Label = 
		return , nil
	}

	 := &Participant{
		ID:       ,
		Label:    ,
		Index:    len(.Participants),
		declared: true,
	}
	.Participants = append(.Participants, )
	[] = 
	return , nil
}

// parseBoxTitle extracts the display title from a box opener's argument:
// an optional leading color (functional rgb()/hsl(), #hex, or a CSS color
// name — mermaid fills the box with it, ASCII has no use for it) followed by
// the title text. <br> tags become spaces, as elsewhere in single-line ASCII.
func parseBoxTitle( string) string {
	 = strings.TrimSpace(brTagRegex.ReplaceAllString(, " "))
	if  := boxColorFuncRegex.FindStringIndex();  != nil {
		return strings.TrimSpace([[1]:])
	}
	if  := boxHexColorRegex.FindStringIndex();  != nil {
		return strings.TrimSpace([[1]:])
	}
	 := 
	if  := strings.IndexAny(, " \t");  >= 0 {
		 = [:]
	}
	if cssColorNames[strings.ToLower()] {
		return strings.TrimSpace([len():])
	}
	return 
}

// cssColorNames is the set of CSS color keywords (plus "transparent") that
// mermaid accepts as a box fill. Needed to split "box Green New serwis"
// (color Green, title "New serwis") from "box Facade" (no color, title
// "Facade") the way mermaid does.
var cssColorNames = func() map[string]bool {
	const  = "aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue " +
		"blueviolet brown burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk crimson " +
		"cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkgrey darkkhaki darkmagenta " +
		"darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray " +
		"darkslategrey darkturquoise darkviolet deeppink deepskyblue dimgray dimgrey dodgerblue firebrick " +
		"floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow grey " +
		"honeydew hotpink indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon " +
		"lightblue lightcoral lightcyan lightgoldenrodyellow lightgray lightgreen lightgrey lightpink " +
		"lightsalmon lightseagreen lightskyblue lightslategray lightslategrey lightsteelblue lightyellow " +
		"lime limegreen linen magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple " +
		"mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue " +
		"mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid " +
		"palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum " +
		"powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen " +
		"seashell sienna silver skyblue slateblue slategray slategrey snow springgreen steelblue tan teal " +
		"thistle tomato turquoise violet wheat white whitesmoke yellow yellowgreen transparent"
	 := map[string]bool{}
	for ,  := range strings.Fields() {
		[] = true
	}
	return 
}()

// findArrow returns the index and token of the first arrow in line, skipping
// quoted spans. This mirrors mermaid's lexer, where a name may contain '-'
// (Alice-in-Wonderland) or spaces (cron job) because only a '-' or '<' that
// starts a real arrow token can end it.
func findArrow( string) (int, string) {
	 := false
	for  := 0;  < len(); ++ {
		switch {
		case [] == '"':
			 = !
		case ! && ([] == '-' || [] == '<'):
			for ,  := range arrowTokens {
				if strings.HasPrefix([:], ) {
					return , 
				}
			}
		}
	}
	return -1, ""
}

// validName reports whether an unquoted participant name is acceptable.
// Mermaid's ACTOR token excludes these characters; anything else (spaces,
// dashes not forming an arrow, '=', '.', ...) is a legal name.
func validName( string) bool {
	return  != "" && !strings.ContainsAny(, `"<>:,;(`)
}

// parseName extracts a participant name: either a quoted string or a bare
// name validated by validName.
func parseName( string) (string, bool) {
	 = strings.TrimSpace()
	if len() >= 2 && strings.HasPrefix(, `"`) && strings.HasSuffix(, `"`) {
		 := [1 : len()-1]
		return ,  != "" && !strings.Contains(, `"`)
	}
	return , validName()
}

// splitMessage breaks a line into [From][()][arrow][()][To]: [Label], where
// "()" marks a central connection on that side. ok is false when the line is
// not a message, so parsing can fall through to the other statement forms.
func splitMessage( string) ( messageParts,  bool) {
	,  := findArrow()
	if  < 0 {
		return
	}
	.arrow = 

	 := strings.TrimSpace([:])
	// A line opening with a fragment keyword is a fragment statement whose
	// label happens to contain an arrow, never a message. Quoted names are
	// exempt: `"loop svc" ->> B` is an explicit participant reference.
	if !strings.HasPrefix(, `"`) && fragmentKeywordRegex.MatchString() {
		return
	}
	if strings.HasSuffix(, "()") {
		.centralFrom = true
		 = strings.TrimSpace(strings.TrimSuffix(, "()"))
	}
	,  := parseName()
	.fromID = 

	// A '+' or '-' after the arrow is the activation shorthand: '+' activates
	// the receiver, '-' deactivates the sender. mermaid's lexer skips
	// whitespace and no name may begin with a sign, so the sign is recognised
	// either side of a space.
	 := strings.TrimLeft([+len():], " \t")
	if  != "" && ([0] == '+' || [0] == '-') {
		.activateTo = [0] == '+'
		.deactivateFrom = [0] == '-'
		 = [1:]
	}
	 = strings.TrimSpace()
	if strings.HasPrefix(, "()") {
		.centralTo = true
		 = strings.TrimSpace(strings.TrimPrefix(, "()"))
	}
	// The label starts at the first ':' after the (possibly quoted) to-name.
	 := 0
	if strings.HasPrefix(, `"`) {
		if  := strings.Index([1:], `"`);  >= 0 {
			 =  + 2
		}
	}
	 := strings.Index([:], ":")
	if  < 0 {
		return
	}
	 += 
	,  := parseName([:])
	.toID = 
	.label = strings.TrimSpace([+1:])

	 =  && 
	return
}

// messageParts is the decomposition of a message line: endpoints, arrow, label,
// central-connection markers and the activation shorthand suffix.
type messageParts struct {
	fromID, arrow, toID, label string
	centralFrom, centralTo     bool
	activateTo                 bool // "+" after the arrow: activate the receiver
	deactivateFrom             bool // "-" after the arrow: deactivate the sender
}

func ( *SequenceDiagram) ( string,  map[string]*Participant,  map[*Participant]int) (bool, error) {
	,  := splitMessage()
	if ! {
		return false, nil
	}

	 := .getParticipant(.fromID, )
	 := .getParticipant(.toID, )

	var  ArrowType
	switch .arrow {
	case "->>":
		 = SolidArrow
	case "-->>":
		 = DottedArrow
	case "->":
		 = SolidOpen
	case "-->":
		 = DottedOpen
	case "-x":
		 = SolidCross
	case "--x":
		 = DottedCross
	case "-)":
		 = SolidPoint
	case "--)":
		 = DottedPoint
	case "<<->>":
		 = BidirectionalSolid
	case "<<-->>":
		 = BidirectionalDotted
	}

	 := 0
	if .Autonumber {
		 = len(.Messages) + 1
	}

	 := &Message{
		From:        ,
		To:          ,
		Label:       .label,
		ArrowType:   ,
		CentralFrom: .centralFrom,
		CentralTo:   .centralTo,
		Number:      ,
	}
	.Messages = append(.Messages, )
	.Events = append(.Events, Event{Kind: EventMessage, Message: })

	// Activation shorthand: the period starts (or ends) after the message that
	// carries the suffix, so the arrow itself sits on the boundary.
	if .activateTo {
		[]++
		.Events = append(.Events, Event{Kind: EventActivate, Participant: })
	}
	if .deactivateFrom {
		if [] == 0 {
			return true, fmt.Errorf("trying to deactivate an inactive participant %q", .ID)
		}
		[]--
		.Events = append(.Events, Event{Kind: EventDeactivate, Participant: })
	}
	return true, nil
}

func ( *SequenceDiagram) ( string,  map[string]*Participant) *Participant {
	if ,  := [];  {
		return 
	}

	 := &Participant{
		ID:    ,
		Label: ,
		Index: len(.Participants),
	}
	.Participants = append(.Participants, )
	[] = 
	return 
}